#include "XmlSerializer.h"



#include <Defines.h>
#include <CampaignItem.h>
#include <ItemGroup.h>
#include <Item.h>
#include <ItemReference.h>
#include <ItemFactory.h>


#include <QDomAttr>



XmlSerializer::XmlSerializer(QObject *parent) :
    AbstractSerializer(parent)
{
}



void XmlSerializer::serialize(AbstractItem *source, QIODevice *output)
{
    if (!output) return;

    QDomDocument doc("ItemXml");

    QDomElement root = toXmlElem(source, doc);
    if (root.isNull()) return;

    doc.appendChild(root);

    QByteArray doc_content = doc.toByteArray(4);
    qDebug(doc_content);
    output->write(doc_content);
}



AbstractItem* XmlSerializer::deserialize(QIODevice* input)
{
    //qDebug("Deserializing");
    QDomDocument doc;
    if (!doc.setContent(input)) return 0;

    QDomElement root = doc.documentElement();


    return fromXmlElem(root);
}



QDomElement XmlSerializer::toXmlElem(AbstractItem *source, QDomDocument doc)
{
    if (!source) return QDomElement();

    if (source->category() == ItemCategory_Root)
    {
        if (dynamic_cast<AbstractItem*>(source->parent())) return QDomElement();
    }


    QString tag = source->metaObject()->className();
    QDomElement elem = doc.createElement(tag);
    for (int field = 0; field < source->fieldCount(); field++)
    {
        QString attr = source->fieldName(field);
        if (attr.isEmpty()) continue;

        QString data = source->data(field, Qt::EditRole).toString();
        if (data.isEmpty()) continue;

        elem.setAttribute(source->fieldName(field), source->data(field, Qt::EditRole).toString());
    }

    foreach (AbstractItem* item, source->items())
    {
        QDomElement child = toXmlElem(item, doc);
        if (child.isNull()) continue;

        elem.appendChild(child);
    }

    return elem;
}



AbstractItem* XmlSerializer::fromXmlElem(QDomElement source, AbstractItem* parent)
{
    //qDebug("From XML");

    AbstractItem* item = ItemFactory::create(source.tagName(), parent);
    if (!item) return 0;

    // get item content
    QDomNamedNodeMap named_nodes = source.attributes();
    for (int i = 0; i < named_nodes.count(); i++)
    {
        QDomAttr attribute = named_nodes.item(i).toAttr();
        if (attribute.isNull()) continue;

        int data_type = item->field(attribute.name());

        item->setData(data_type, attribute.value());
    }


    for (QDomElement elem = source.firstChildElement(); !elem.isNull(); elem = elem.nextSiblingElement())
    {
        AbstractItem* child = fromXmlElem(elem, item);
        if (!child) continue;

    }


    return item;
}


